<script>
import * as echarts from 'echarts'
import { debounce } from '@/utils/index'
export default {
    props: {
        /**
         * [
         *      {
         *          label:string,
         *          value:number
         *      }
         * ]
         */
        data: {
            type: Array,
            required: true,
            default() {
                return []
            }
        },
        /**
         * [
         *      {
                    from:'',
                    to:''
                }
         * ]
         */
        colors: [],
        width: {
            default: '100%',
        },
        height: {
            default: '300px',
        },
        unit:{
            type:String,
            default:'人'
        }
    },
    components: {},
    data() {
        return {
            chart: null,
            chartResizingWithDebounce: debounce(this.chartResizing, 200)
        }
    },
    computed: {
        buildStyles() {
            const { width, height } = this
            return {
                width, height
            }
        }
    },
    watch: {
        data: function (data) {
            if (!Array.isArray(data) || data.length <= 0) return []
            this.chart?.setOption?.(this.buildOptions())
        }
    },
    methods: {
        chartResizing() {
            this.chart?.resize?.({
                animation: {
                    duration: 1500,
                    easing: 'elasticOut'
                }
            })
        },
        buildSeries(data) {
            let count = 0
            const seriesOption = data.map((item, index) => {

                count += item.percentage;
                return {
                    type: 'bar',
                    data: [null, null, null, count],
                    coordinateSystem: 'polar',
                    z: 9999 - index,
                    name: item.label,
                    roundCap: true,
                    // color: color[index],
                    barGap: '-100%',
                    itemStyle: {
                        normal: {
                            shadowBlur: 0,
                            // shadowColor: color[index],
                        },
                    },
                }
            })

            return seriesOption
        },
        buildColors() {
            return this.colors.map(item => {
                const { from, to } = item
                return {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                        {
                            offset: 0,
                            color: from,
                        },
                        {
                            offset: 1,
                            color: to,
                        },
                    ],
                }
            })
        },
        buildOptions() {
            let data = this.data

            // 计算总量
            let total = data.reduce((prev,current) => {
                return prev + current.value
            },0)

            let withPercentage = data.map(item => {
                const {label,value} = item
                let percentage = parseFloat((value / total * 100).toFixed(2))
                return {
                    label,
                    value,
                    percentage
                }
            })

            let map = new Map()
            for(let item of withPercentage){
                map.set(item.label,item)
            }

            let max = withPercentage.reduce((prev,current) => {
                if(prev === null)
                    return current

                    if (isNaN(prev.percentage) || isNaN(current.percentage)) {
                        prev.percentage = 100;
                        current.percentage = 100;
                    }
                if(prev.percentage < current.percentage)
                    return current

                return prev
            },null)

            const series = this.buildSeries(withPercentage)

            const options = {
                backgroundColor: 'white',
                title: {
                    left: '20%',
                    top: '50%',
                    textAlign: 'center',
                    textVerticalAlign: 'middle',
                    textStyle: {
                        lineHeight: 28,
                        rich: {
                            line1: {
                                color: '#BBBBBB',
                                fontSize: 14,
                            },
                            line2: {
                                color: '#000000',
                                fontSize: 18,
                                fontWeight: 'bold',
                            },
                        },
                    },
                    text: [
                        `{line1|${max?.label} 占比 ${max?.percentage}% }\n`,
                        `{line2|${max?.value}${this.unit}}`,
                    ].join(''),
                },
                tooltip: {
                    show: true,
                    formatter: (params) => {
                        const lines = [],
                              data = map.get(params.seriesName)
                        lines.push(params.seriesName)
                        lines.push(`${data.value}${this.unit}`)

                        return lines.join('<br />')
                    }
                },
                legend: {
                    show: true,
                    icon: 'circle',
                    orient: 'vertical',
                    x: 'right',
                    top: 'middle',
                    left: '50%',
                    textStyle: {
                        lineHeight: 26,
                        color: '#3D3D3D',
                        fontSize: 18,
                        rich: {
                            percentage: {
                                fontSize: 13,
                                color: '#BBBBBB',
                            },
                            value: {
                                fontSize: 13,
                                color: '#8E8E8E',
                            }
                        },
                    },
                    itemGap: 16,
                    formatter: (params) => {
                        let data = map.get(params)
                        return [`{params|${data.label}}`, `{percentage|${data.percentage}%}`, `{value|${data.value}${this.unit}}`].join("\t\t\t")
                    }
                },
                angleAxis: {
                    axisLine: {
                        show: false,
                    },
                    axisLabel: {
                        show: false,
                    },
                    splitLine: {
                        show: false,
                    },
                    axisTick: {
                        show: false,
                    },
                    min: 0,
                    max: 100,
                    boundaryGap: ['0', '100'],
                    startAngle: 90,
                },
                radiusAxis: {
                    type: 'category',
                    axisLine: {
                        show: false,
                    },
                    axisTick: {
                        show: false,
                    },
                    axisLabel: {
                        show: false,
                    },
                    z: 10,
                },
                polar: {
                    radius: '70%',
                    center: ['20%', '50%']
                },
                toolbox: {
                    show: false,
                },
                series,
            };
            return options
        }
    },
    mounted() {
        this.chart = echarts.init(this.$refs.ringChart)
        this.chart.setOption(this.buildOptions())
        console.log(this.buildOptions())
        window.addEventListener('resize', this.chartResizingWithDebounce)
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.chartResizingWithDebounce)
        this.chart?.dispose?.()
    }
}
</script>

<template>
    <div ref="ringChart" :style="buildStyles" />
</template>

<style lang="scss"></style>